package io.p2p.stream.dispatch.controller;

import com.alibaba.fastjson.JSONObject;
import io.p2p.stream.dispatch.model.ClientSharedModel;
import io.p2p.stream.dispatch.service.DispatchUdpServer;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;

import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import common.core.util.AvailableIPUtil;
import common.core.util.RandomUtil;

public class IndexController {
    @FXML
    private Button btnConnect;
    @FXML
    private TextField txtUserName;
    private DispatchUdpServer baseUdpServer;

    @FXML
    private void btnConnectClick(ActionEvent event) throws UnknownHostException {

        btnConnect.setDisable(true);

        ClientSharedModel.loginName = txtUserName.getText().trim();

        baseUdpServer = new DispatchUdpServer();
        baseUdpServer.start(AvailableIPUtil.getAvailableIP(), RandomUtil.getRandomNumber(6000,7000));

        JSONObject loginJson = new JSONObject();
        loginJson.put("type","mainlineLogin");
        loginJson.put("name", ClientSharedModel.loginName);

        baseUdpServer.send(loginJson.toJSONString(),new InetSocketAddress(ClientSharedModel.mainServerFirstIP
                ,ClientSharedModel.mainServerFirstPort));
    }
}